#!/usr/bin/env ruby

require 'json'
require 'yaml'

path = File.absolute_path(ARGV.shift)

puts "Merging reports from #{path}"
Dir.glob(path + "/*_main_rspec_report.json").each do |main_report_file|
  main_report = JSON.parse(File.read(main_report_file))
  new_report = main_report.dup
  main_file_name = File.basename(main_report_file)
  match = main_file_name.match(/(?<DISTRO_NAME>.*?)_(?<DISTRO_VERSION>.*?)_.*/)
  os = match['DISTRO_NAME']
  version = match['DISTRO_VERSION']
  puts "#{os} #{version}"
  Dir.glob(path + "/#{os}_#{version}_rspec_node_*").each do |report_file|
    report = JSON.parse(File.read(report_file))

    # Remove existing values
    updates = report.delete_if do |key, value|
      main_report[key] && main_report[key] == value
    end
    new_report.merge!(updates)

    puts "\tMerged #{report_file} adding #{updates.size} results."
  end

  File.write(main_report_file, JSON.pretty_generate(new_report))
  puts "\tSaved #{main_report_file}."
end
